import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Divider, Drawer, Button, Radio, Modal, Input, Table, Tag, Transfer, Pagination, message } from 'antd';
import styles from "./index.less";
import { spawn } from 'child_process';
import zl2 from '@/assets/icons/zl2.png'
import zl1 from '@/assets/icons/zl1.png'
import zl3 from '@/assets/icons/zl3.png'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Search = Input.Search;

class TemplatePg extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      total: '',
      datalist: [],
      limit: 6,
      page: 1,
      name: '',
      parameterList: [],
      zyIf: '',
      mockData: [],
      targetKeys: [],
      mockdata: [],
      arrInput: {},
      placeholder: [],
      submitList: [],// 待修改数据
      agtcx: false,
      addtep: false,
      id: null,
      totaltime: '',
      selectedKeys: [],
      bc: [],
      key: '',
      accumulationList: [],
      mockdataB: [],
      mockdataTwo: [],
      awaitList: [],
      selectedRowKeys: [],
      selectedRowKeysTwo: [],
      selectedRowKeysOne: []
    }
  }

  componentDidMount() {
    this.fetch()

  }

  fetch = () => {
    const { dispatch, currentUser } = this.props;
    const { page, limit, key } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'extendRt/fetch',
        payload: { key, page, limit },
        callback: res => {
          console.log('获取相似问模板列表', res);
          let temp = res.item
          temp.map((item, index) => item['key'] = index)
          this.setState({
            datalist: temp,
            total: res.total
          })
        },
      });
    });
  }

  fetchb = (id, page = 1, values = '') => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'extendRt/fetchb',
        payload: { _id: id, page, limit: 99999, values },
        callback: res => {
          console.log('获取相似问模板列表', res);
          let temp = res.items
          let list = []
          temp.map((item) => {
            let obj = {}
            obj.question = item
            list.push(obj)
          })
          this.setState({
            mockdataB: list,
            mockdata: temp,
            totaltime: res.total
          }, () => {
            // this.getMock()
          })
        },
      });
    });
  }

  showModal = () => {
    this.props.form.setFields({ "businessName": "" })
    this.props.form.resetFields();
    this.setState({
      visible: true,
      agtcx: false,
    });
  }

  handleOk = () => {
    if (this.state.id === null) {
      message['warning'](`请选择一项`)
    } else {
      // this.getMock();
      this.setState({
        visible: false,
        zyIf: '1',
        addtep: true
      });
    }

  }

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }



  // ---穿梭框结束--

  submitTemplate = () => { // 生成问题
    const { parameterList, arrInput } = this.state
    console.log(parameterList)
    let userInfo = this.props.form.getFieldsValue();
    this.props.form.validateFields((err, values) => {
      console.log(userInfo)
      let user = userInfo
      delete user.businessName
      this.setState({ arrInput: user })
      let pand = []
      for (var o in user) {
        if (userInfo[o] == '') {
          let sz = 1
          pand.push(sz)
        }
      }
      if (pand.length === 0) {

        const { id, page } = this.state
        this.fetchb(id, page, user)
        setTimeout(() => {
          // this.getMock();
          this.setState({ agtcx: true })
        }, 500)
      } else {
        message['warning']('输入框不能为空')
      }

    })


  }

  submitknowledge = () => {
    const { mockData, id, bc, submitList, accumulationList, selectedKeys } = this.state
    let arr = []
    bc.map((item) => {
      arr.push(mockData[item].title)
    })
    // this.props.templateData(arr)

    console.log(selectedKeys, submitList)
    if (submitList.length) {
      this.setState({ accumulationList: [...accumulationList, ...submitList] }, () => {
        console.log(this.state.accumulationList)
        this.props.templateData(this.state.accumulationList)
        setTimeout(() => {
          this.setState({ selectedKeys: [], submitList: [] }, () => {
            this.submitTemplate()
          })
        }, 100)
      })
    } else {
      message.error('添加项为空')
    }
  }

  // 取消 清空选中数据
  submitknowledgeCancel = () => {
    const { id, arrInput, page } = this.state
    this.setState({ selectedKeys: [] })
  }



  onChangeA = (val) => {
    console.log(val) //parameterList: arrkey, parameterDate: date
    this.setState({ page: val, selectedRowKeys: [], selectedRows: [], parameterList: [], parameterDate: [], }, () => {
      this.fetch()
    })
  }

  pagintime = (val) => { //清空数据
    console.log(val)
    const { id, arrInput, page } = this.state
    this.setState({ selectedKeys: [] })
    this.fetchb(id, val, arrInput)

  }

  add = (item) => {
    console.log(item)
    this.setState({ selectedRowKeys: [] })
    const { awaitList } = this.state
    let a = {}
    a.question = item.question
    awaitList.push(a)
    let temp = [];
    for (let i = 0; i < awaitList.length; i++) {
      if (temp.indexOf(awaitList[i].question) == -1) {
        temp.push(awaitList[i].question);
      }
    }
    let list = []
    temp.map((item, index) => {
      let obj = {}
      obj.question = item
      obj.key = index
      list.push(obj)
    })
    console.log(list)
    this.setState({ awaitList: list })
  }

  batchAdd = () => {
    const { awaitList, mockdataTwo } = this.state
    let merge = [...awaitList, ...mockdataTwo]
    let temp = [];
    for (let i = 0; i < merge.length; i++) {
      if (temp.indexOf(merge[i].question) == -1) {
        temp.push(merge[i].question);
      }
    }
    console.log(temp)
    let list = []
    temp.map((item) => {
      let obj = {}
      obj.question = item
      list.push(obj)
    })
    this.setState({ awaitList: list, selectedRowKeysOne: [] })
  }

  remove = (item) => {
    const { awaitList } = this.state
    console.log(awaitList.filter(val => val.question != item))
    this.setState({ awaitList: awaitList.filter(val => val.question != item) })
    this.setState({ selectedRowKeysTwo: [] })
  }

  batchRemove = () => {
    const { awaitList, submitList } = this.state
    console.log(awaitList, submitList)
    for (let i = 0; i < submitList.length; i++) {
      for (let j = 0; j < awaitList.length; j++) {
        if (awaitList[j].question == submitList[i].question) {
          awaitList.splice(j, 1)
        }
      }
    }
    console.log(awaitList);
    this.setState({ awaitList, selectedRowKeys: [], selectedRowKeysTwo: [] })
  }

  submitknowledge = () => {
    const { awaitList } = this.state
    // console.log(awaitList)
    if(awaitList.length){
      let arr = []
      awaitList.map((item)=>{
       arr.push(item.question)
      })
      console.log(arr)
      this.props.templateData(arr)
      this.setState({awaitList:[],selectedRowKeysTwo:[],selectedRowKeys:[]})
    }else{
      message.error('添加项为空')
    }
  }



  render() {
    const columns = [
      {
        title: () => {
          return (
            <div>
              <span>问题库</span>
              <Button onClick={this.batchAdd} size='small' style={{ float: 'right' }}>批量添加</Button>
            </div>
          )
        },
        width: 'calc(100vw)',
        fixed: 'left',
        dataIndex: 'question',
        render: (question, val) => {
          return <div className={styles.listPb}>
            <span dangerouslySetInnerHTML={{ __html: question }} className={styles.ellipsisB} style={{ width: 380 }}>
            </span>
            <img style={{ marginLeft: 10 }} onClick={() => { this.add(val) }} src={zl2} />
          </div>
        }
      },
    ]
    const columnsTwo = [
      {
        title: () => {
          return (
            <div>
              <span>待添加</span>
              <Button onClick={this.batchRemove} size='small' style={{ float: 'right' }}>批量移除</Button>
            </div>
          )
        },
        width: 'calc(100vw)',
        fixed: 'left',
        dataIndex: 'question',
        render: (question, val) => {
          return <div className={styles.listPb}>
            <span dangerouslySetInnerHTML={{ __html: question }} className={styles.ellipsisB} style={{ width: 380 }}>
            </span>
            <img style={{ marginLeft: 10 }} onClick={() => { this.remove(question) }} src={zl3} />
          </div>
        }
      },
    ]
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys, selectedRowKeysTwo, submitList, selectedRowKeysOne } = this.state;
    const rowSelectionOne = {
      selectedRowKeys: selectedRowKeysOne,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRowKeys, 'selectedRows: ', selectedRows);
        let list = []
        selectedRows.map((item, index) => {
          let obj = {}
          obj.question = item.question
          obj.key = index
          list.push(obj)
        })
        console.log(list)
        this.setState({ selectedRowKeysOne: selectedRowKeys, mockdataTwo: list })
      },
    };
    const rowSelectionTwo = {
      selectedRowKeys: selectedRowKeysTwo,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRowKeys, 'selectedRows: ', selectedRows);
        this.setState({ selectedRowKeysTwo: selectedRowKeys, submitList: selectedRows })
      },
      // getCheckboxProps: record => ({
      //   checked: (arr.indexOf(record.question)>-1?true:false)
      // }),
    };
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 2
      },
      wrapperCol: {
        xs: 24,
        sm: 22
      }
    }
    let color;
    const date = [];
    let qs = []
    let ad = []
    const columns1 = [
      {
        dataIndex: 'name',
        align: 'left',
        render: (name, index) => {
          let key = index.key
          let a = name;
          let b = /\${.*?\}/g;
          let end;
          let data = name
          let indx = []
          let sa = a.replace(b, (word) => {
            end = word.slice(2, -1)
            let tcx = 'tcx'
            indx.push(tcx)
            if (indx.length % 2 == 1) {
              return `<span style="background-color:#87d3ac ;color: #ffffff;padding: 5px;margin: 0 10px;border-radius:5px; "}} >${end}</span>`
            } else {
              return `<span style="background-color:#5092e1;color: #ffffff;padding: 5px;margin: 0 10px;border-radius:5px; "}} >${end}</span>`
            }

          });
          return (
            //标签出不来
            <div dangerouslySetInnerHTML={{ __html: sa }}></div>
          )
        }
      }
    ]
    const { datalist } = this.state
    const rowSelection = {
      type: 'radio',
      datalist,
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => { // 单选数据 this.fetchb(this.state.id)
        console.log(selectedRows[0], selectedRowKeys)
        this.setState({ selectedRowKeys, selectedRows })
        let i = 0
        let key = i
        let a = selectedRows[0].name;
        let b = /\${.*?\}/g;
        let end;
        let indx = []
        let sa = a.replace(b, (word) => {
          end = word.slice(2, -1)
          let tcx = 'tcx'
          indx.push(tcx)
          //标签出不来
          if (indx.length % 2 === 1) {
            return `<span style="background-color:#87d3ac ;color: #ffffff;padding: 5px;margin: 0 10px;border-radius:5px; "}} >${end}</span>`
          } else {
            return `<span style="background-color:#5092e1;color: #ffffff;padding: 5px;margin: 0 10px;border-radius:5px; "}} >${end}</span>`
          }
        });
        this.setState({
          name: sa,
          id: selectedRows[0]._id
        }, () => {
          this.fetchb(this.state.id)
        })
        let arrkey = selectedRows[0].placeholder
        arrkey.map((item, index) => {
          let b = /\${.*?\}/g;
          let end;
          let sa = item.replace(b, (word, key) => {
            end = word.slice(2, -1)
            date.push(end)
          });
        })
        console.log(date)
        this.setState({ parameterList: arrkey, parameterDate: date, })
      }
    }
    const titles = ['问题库', '待添加']
    return (
      <div>
        <Form layout='horizontal' className='antA'>
          <FormItem className='antColor' label='添加模版'  {...FormItemLayont}>
            <div style={{ marginLeft: 30 }}>
              {this.state.zyIf === '' ? <Button onClick={this.showModal}>添加模版</Button> : <span dangerouslySetInnerHTML={{ __html: this.state.name }}></span>}
              {this.state.zyIf === '' ? '' : <Button style={{ marginLeft: 10 }} onClick={this.showModal}>修改模版</Button>}
            </div>
          </FormItem>
          {this.state.addtep === false ? '' : <FormItem className='antColor' label='模版参数' {...FormItemLayont}>
            <div style={{ marginLeft: 30, display: 'flex', flexWrap: 'wrap' }} >
              {this.state.zyIf === '' ? '' : this.state.parameterList.map((item, index) => {
                let color = index % 2 == 1 ? '#87d3ac' : '#5092e1';
                let itm = item.slice(2, -1)
                return (
                  <span>
                    <Tag color={color}>{itm}</Tag>
                    <span>=</span>
                    <span>
                      {getFieldDecorator(`${item}`, {
                        initialValue: '',
                      })(

                        <Input
                          id={index}
                          style={{ width: 125, marginRight: 10, marginLeft: 10 }}
                          onChange={this.onInput}
                        />
                      )}

                    </span>
                  </span>
                );
              })}
              <Button onClick={this.submitTemplate} style={{ marginTop: 4 }}>生成问题</Button>
            </div>
          </FormItem>}

        </Form>

        {
          this.state.agtcx === false ? '' : <Row style={{ marginTop: 20 }} gutter={0}>
            <Col style={{maxWidth:500}} span={11}>
              <div className={styles.bk}>
                <div className='listZdys'>
                  <Table
                    scroll={{ y: 544 }}
                    rowSelection={rowSelectionOne}
                    columns={columns}
                    dataSource={this.state.mockdataB}// 数据
                    pagination={false}
                  />
                </div>
              </div>
            </Col>
            <Col className={styles.imgJz} span={2}>
              <img src={zl1} />
            </Col>
            <Col style={{maxWidth:500}} span={11}>
              <div className={styles.bk}>
                <div className='listZdys'>
                  <Table
                    scroll={{ y: 544 }}
                    rowSelection={rowSelectionTwo}
                    columns={columnsTwo}
                    dataSource={this.state.awaitList}// 数据
                    pagination={false}
                  />
                </div>
              </div>
            </Col>
          </Row>
        }
        {/* <Button style={{marginLeft:10}}  onClick={this.submitknowledgeCancel} style={{ marginLeft: 20 }}>取消</Button> */}
        {this.state.agtcx === false ? '' : <div style={{ float: 'right', marginRight: 50 }} className='zdyButtonA'><Button type='primary' onClick={this.submitknowledge} style={{ marginTop: 20 }}>添加到知识点</Button></div>}

        <Modal
          style={{ minWidth: 620 }}
          className='antbackround'
          title="选择问题模版"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form layout="horizontal" className='ant'>
            <FormItem >
              {getFieldDecorator('businessName', {
                initialValue: '',
              })(
                // this.props.form.setFields({ "businessName": "" })
                <Search
                  style={{ width: 390, marginLeft: 87 }}
                  placeholder="请输入搜索内容"
                  onSearch={value => {
                    this.setState({ key: value, page: 1 }, () => {
                      this.fetch()
                    })
                  }}
                />
              )}
            </FormItem>
            <FormItem >
              <Table
                rowSelection={rowSelection}
                className='antTable'
                columns={columns1}
                dataSource={this.state.datalist}//数据
                // onChange={this.handleChange}
                pagination={{  // 分页
                  total: this.state.total, // 数据总数量
                  pageSize: this.state.limit,  // 显示几条一页
                  current: this.state.page, // 默认显示几条一页
                  showQuickJumper: true,
                  onChange: this.onChangeA,
                }}
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }




}
export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(TemplatePg));

